package com.begye.smartloan.apptest.renzheng.document

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtRenZhengDocumentBinding
import com.begye.smartloan.apptest.ext.addBold
import com.begye.smartloan.apptest.ext.addNormal
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.alldone.RenZhengAllDoneActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.dialog.DocumentSourceTypeDialogFragment
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog


@SuppressLint("CustomWelcomeScreen")
class RenZhengDocumentActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtRenZhengDocumentBinding

    private lateinit var _pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    private val _renZhengDocumentViewModel by lazy {
        ViewModelProvider(this)[RenZhengDocumentViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtRenZhengDocumentBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
    }

    private fun configYongHuLiuChengState() {

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = RenZhengAllDoneActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP,
                    params = hashMapOf<String, String>().apply {
                        put("titles", it)
                    }
                )
            }
        }
    }

    private fun configUIState() {

        _renZhengDocumentViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _renZhengDocumentViewModel.onSaveDocumentSuccessStateLiveData.observe(this) {
            _yongHuLiuChengViewModel.requestYongHuLiuCheng()
        }
    }

    private fun configUIEvent() {

        _binding.atRenZhengNav.initConfig(
            text = getString(R.string.fill_text_53),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                if (LoginTool.filterAdType()) {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        // 跳转相册监听
        _pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    _renZhengDocumentViewModel.handlePhotoAlbumResult(
                        this@RenZhengDocumentActivity,
                        uri,
                        onConversionCompleted = { type, bitmap, position ->
                            updateImagePathResult(type, bitmap, position)
                        },
                        onUploadCompleted = { type, url, position ->
                            updateImageUrlResult(type, url, position)
                        })
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        _binding.atRenZhengDoingSubmit.setOnClickListener {
            if (_renZhengDocumentViewModel.canSubmit()) {
                _renZhengDocumentViewModel.requestSaveDocument()
            }

            //
            addTouch(type = "ren_zheng_document_commit_click")
        }

        _binding.atRenZhengDocumentTypeIdCardContent.setOnClickListener {
            _binding.atRenZhengDocumentTypeIdCardContent.setBackgroundResource(R.drawable.layer_c12_000000)
            _binding.atRenZhengDocumentTypeDrivingContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)
            _binding.atRenZhengDocumentTypePassportContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)

            _binding.atRenZhengDocumentTypeIdCardIcon.setImageResource(R.drawable.dres_66)
            _binding.atRenZhengDocumentTypeDrivingIcon.setImageResource(R.drawable.dres_68)
            _binding.atRenZhengDocumentTypePassportIcon.setImageResource(R.drawable.dres_74)

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextColor(Color.parseColor("#ffffff"))
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextColor(Color.parseColor("#999999"))
            _binding.atRenZhengDocumentTypePassportTitle.setTextColor(Color.parseColor("#999999"))

            _binding.atRenZhengDocumentTypeIdCardTitle.addBold()
            _binding.atRenZhengDocumentTypeDrivingTitle.addNormal()
            _binding.atRenZhengDocumentTypePassportTitle.addNormal()

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12F)
            _binding.atRenZhengDocumentTypePassportTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_SP,
                12F
            )

            _binding.atRenZhengDocumentTypeIdCardCheckBox.visibility = View.VISIBLE
            _binding.atRenZhengDocumentTypeDrivingCheckBox.visibility = View.INVISIBLE
            _binding.atRenZhengDocumentTypePassportCheckBox.visibility = View.INVISIBLE

            _binding.atRenZhengDocumentIdCardContent.visibility = View.VISIBLE
            _binding.atRenZhengDocumentDrivingContent.visibility = View.GONE
            _binding.atRenZhengDocumentPassportContent.visibility = View.GONE

            //
            addTouch(type = "ren_zheng_document_type_idcard_click")
        }

        _binding.atRenZhengDocumentTypeDrivingContent.setOnClickListener {
            _binding.atRenZhengDocumentTypeIdCardContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)
            _binding.atRenZhengDocumentTypeDrivingContent.setBackgroundResource(R.drawable.layer_c12_000000)
            _binding.atRenZhengDocumentTypePassportContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)

            _binding.atRenZhengDocumentTypeIdCardIcon.setImageResource(R.drawable.dres_71)
            _binding.atRenZhengDocumentTypeDrivingIcon.setImageResource(R.drawable.dres_73)
            _binding.atRenZhengDocumentTypePassportIcon.setImageResource(R.drawable.dres_74)

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextColor(Color.parseColor("#999999"))
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextColor(Color.parseColor("#ffffff"))
            _binding.atRenZhengDocumentTypePassportTitle.setTextColor(Color.parseColor("#999999"))

            _binding.atRenZhengDocumentTypeIdCardTitle.addNormal()
            _binding.atRenZhengDocumentTypeDrivingTitle.addBold()
            _binding.atRenZhengDocumentTypePassportTitle.addNormal()

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12F)
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
            _binding.atRenZhengDocumentTypePassportTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_SP,
                12F
            )

            _binding.atRenZhengDocumentTypeIdCardCheckBox.visibility = View.INVISIBLE
            _binding.atRenZhengDocumentTypeDrivingCheckBox.visibility = View.VISIBLE
            _binding.atRenZhengDocumentTypePassportCheckBox.visibility = View.INVISIBLE

            _binding.atRenZhengDocumentIdCardContent.visibility = View.GONE
            _binding.atRenZhengDocumentDrivingContent.visibility = View.VISIBLE
            _binding.atRenZhengDocumentPassportContent.visibility = View.GONE

            //
            addTouch(type = "ren_zheng_document_type_driving_click")
        }

        _binding.atRenZhengDocumentTypePassportContent.setOnClickListener {
            _binding.atRenZhengDocumentTypeIdCardContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)
            _binding.atRenZhengDocumentTypeDrivingContent.setBackgroundResource(R.drawable.layer_c12_000000_stroke)
            _binding.atRenZhengDocumentTypePassportContent.setBackgroundResource(R.drawable.layer_c12_000000)

            _binding.atRenZhengDocumentTypeIdCardIcon.setImageResource(R.drawable.dres_71)
            _binding.atRenZhengDocumentTypeDrivingIcon.setImageResource(R.drawable.dres_68)
            _binding.atRenZhengDocumentTypePassportIcon.setImageResource(R.drawable.dres_72)

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextColor(Color.parseColor("#999999"))
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextColor(Color.parseColor("#999999"))
            _binding.atRenZhengDocumentTypePassportTitle.setTextColor(Color.parseColor("#ffffff"))

            _binding.atRenZhengDocumentTypeIdCardTitle.addNormal()
            _binding.atRenZhengDocumentTypeDrivingTitle.addNormal()
            _binding.atRenZhengDocumentTypePassportTitle.addBold()

            _binding.atRenZhengDocumentTypeIdCardTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12F)
            _binding.atRenZhengDocumentTypeDrivingTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12F)
            _binding.atRenZhengDocumentTypePassportTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_SP,
                14F
            )

            _binding.atRenZhengDocumentTypeIdCardCheckBox.visibility = View.INVISIBLE
            _binding.atRenZhengDocumentTypeDrivingCheckBox.visibility = View.INVISIBLE
            _binding.atRenZhengDocumentTypePassportCheckBox.visibility = View.VISIBLE

            _binding.atRenZhengDocumentIdCardContent.visibility = View.GONE
            _binding.atRenZhengDocumentDrivingContent.visibility = View.GONE
            _binding.atRenZhengDocumentPassportContent.visibility = View.VISIBLE

            //
            addTouch(type = "ren_zheng_document_type_passport_click")
        }

        _binding.atRenZhengDocumentIdCardFrontImageContent.setOnClickListener {
            //
            addTouch(type = "ren_zheng_document_type_idcard_front_click")

            toDocumentCaptureActivity(0, 0)
        }

        _binding.atRenZhengDocumentIdCardBackImageContent.setOnClickListener {
            //
            addTouch(type = "ren_zheng_document_type_idcard_back_click")

            toDocumentCaptureActivity(0, 1)
        }

        _binding.atRenZhengDocumentDrivingFrontImageContent.setOnClickListener {
            //
            addTouch(type = "ren_zheng_document_type_driving_front_click")

            toDocumentCaptureActivity(1, 0)
        }

        _binding.atRenZhengDocumentDrivingBackImageContent.setOnClickListener {
            //
            addTouch(type = "ren_zheng_document_type_driving_back_click")

            toDocumentCaptureActivity(1, 1)
        }

        _binding.atRenZhengDocumentPassportContent.setOnClickListener {
            //
            addTouch(type = "ren_zheng_document_type_passport_front_click")

            toDocumentCaptureActivity(2, 0)
        }
    }

    private fun checkPermission(): Boolean {
        return EasyPermissions.hasPermissions(
            this,
            android.Manifest.permission.CAMERA
        )
    }

    private fun requestPermission() {
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            300,
            android.Manifest.permission.CAMERA
        )
    }

    private fun toDocumentCaptureActivity(type: Int, position: Int) {
        _renZhengDocumentViewModel.documentType = type
        _renZhengDocumentViewModel.documentPosition = position

        if (checkPermission()) {
            val dialog = DocumentSourceTypeDialogFragment {
                if (DocumentSourceTypeDialogFragment.TYPE_TAKE_PIC == it) {
                    val intent = Intent(
                        this@RenZhengDocumentActivity,
                        RenZhengDocumentCaptureActivity::class.java
                    )
                    intent.putExtra("type", type.toString())
                    intent.putExtra("position", position.toString())
                    startActivityForResult(
                        intent,
                        RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE
                    )

                } else if (DocumentSourceTypeDialogFragment.TYPE_PHOTO_ALBUM == it) {
                    _pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
            }
            dialog.showNow(supportFragmentManager, "document")

        } else {
            requestPermission()
        }
    }

    /**
     * 选择图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param bitmap 图片Bitmap对象
     * @param position 位置，0：第一张，1：第二张
     */
    private fun updateImagePathResult(type: Int, bitmap: Bitmap?, position: Int) {
        if (type == 0) {
            if (position == 0) {
                if (bitmap != null) {
                    _binding.atRenZhengDocumentIdCardFrontImage.setImageBitmap(bitmap)
                } else {
                    _binding.atRenZhengDocumentIdCardFrontImage.setImageResource(R.drawable.dres_69)
                }
            } else if (position == 1) {
                if (bitmap != null) {
                    _binding.atRenZhengDocumentIdCardBackImage.setImageBitmap(bitmap)
                } else {
                    _binding.atRenZhengDocumentIdCardBackImage.setImageResource(R.drawable.dres_70)
                }
            }
        } else if (type == 1) {
            if (position == 0) {
                if (bitmap != null) {
                    _binding.atRenZhengDocumentDrivingFrontImage.setImageBitmap(bitmap)
                } else {
                    _binding.atRenZhengDocumentDrivingFrontImage.setImageResource(R.drawable.dres_69)
                }
            } else if (position == 1) {
                if (bitmap != null) {
                    _binding.atRenZhengDocumentDrivingBackImage.setImageBitmap(bitmap)
                } else {
                    _binding.atRenZhengDocumentDrivingBackImage.setImageResource(R.drawable.dres_70)
                }
            }
        } else if (type == 2) {
            if (bitmap != null) {
                _binding.atRenZhengDocumentPassportFrontImage.setImageBitmap(bitmap)
            } else {
                _binding.atRenZhengDocumentPassportFrontImage.setImageResource(R.drawable.dres_69)
            }
        }
    }

    /**
     * 上传图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param url 图片url
     * @param position 位置，0：第一张，1：第二张
     */
    private fun updateImageUrlResult(type: Int, url: String?, position: Int) {
        if (type == 0) {
            if (position == 0) {
                if (url.isNullOrBlank()) {
                    _binding.atRenZhengDocumentIdCardFrontImage.setImageResource(R.drawable.dres_69)
                }
            } else if (position == 1) {
                if (url.isNullOrBlank()) {
                    _binding.atRenZhengDocumentIdCardBackImage.setImageResource(R.drawable.dres_70)
                }
            }
        } else if (type == 1) {
            if (position == 0) {
                if (url.isNullOrBlank()) {
                    _binding.atRenZhengDocumentDrivingFrontImage.setImageResource(R.drawable.dres_69)
                }
            } else if (position == 1) {
                if (url.isNullOrBlank()) {
                    _binding.atRenZhengDocumentDrivingBackImage.setImageResource(R.drawable.dres_70)
                }
            }
        } else if (type == 2) {
            if (url.isNullOrBlank()) {
                _binding.atRenZhengDocumentPassportFrontImage.setImageResource(R.drawable.dres_69)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        requestPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            requestPermission()

        } else if (requestCode == RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("path")
                // 更新页面
                _renZhengDocumentViewModel.handleTakePictureResult(
                    result = imageOutputPath,
                    onConversionCompleted = { type, bitmap, position ->
                        updateImagePathResult(type, bitmap, position)
                    },
                    onUploadCompleted = { type, url, position ->
                        updateImageUrlResult(type, url, position)
                    })
            }
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

